/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import { Attributes, mergePath } from './build-option-path-info.js';
import { readOpt } from '../project/build-option/build-option-util.js';
import { getJson5Obj } from '../utils/json-util.js';
import { ModuleJson } from '../options/configure/module-json-options.js';
import ModuleObj = ModuleJson.ModuleObj;

class ModuleOptionPathInfo {
  private moduleOptPathMap: Map<string, Attributes> = new Map();

  initModuleOptPathMap(moduleJson5Path: string) {
    const moduleOpt = getJson5Obj(moduleJson5Path) as ModuleObj;
    this.moduleOptPathMap = readOpt(moduleOpt, moduleJson5Path);
  }

  setModuleOptPathMap(moduleJson5Path: string, moduleOpt: ModuleObj, srcPath: string) {
    if (this.moduleOptPathMap.size === 0) {
      this.initModuleOptPathMap(moduleJson5Path);
    }
    const newModuleOpt = readOpt(moduleOpt, srcPath);
    this.moduleOptPathMap = mergePath(this.moduleOptPathMap, newModuleOpt);
  }

  getModuleOptPath(moduleJson5Path: string, optName: string) {
    if (this.moduleOptPathMap.size === 0) {
      this.initModuleOptPathMap(moduleJson5Path);
    }
    return this.moduleOptPathMap.get(optName)?.srcPath ?? moduleJson5Path;
  }
}

export const moduleOptionPathInfo = new ModuleOptionPathInfo();
